import operate from '@dfeidao/atom-nodejs/db/operate';
import query from '@dfeidao/atom-nodejs/db/query';

interface Message {
	productid: string;
	formgroup_no: string;
	_id: string;
}
interface D {
	role_no: string;
	group_id: string;
	_id: string;

}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const systemid = '12';
	const { exec, del } = operate(action_id, session_id, systemid);

	const { exec: e2, prepare } = query(action_id, session_id, systemid);

	prepare('pub_role_allot', ['_id', 'role_no', 'pk_val', 'productid'], { productid: msg.productid, pk_val: msg.formgroup_no }, 199, 1, [], []);
	const [data] = await e2<D>();
	const arr = data.map((v) => {
		return v._id;
	});
	prepare('allot_conditions_group', ['group_id'], { productid: msg.productid, role_allot_id: { $in: arr } }, 199, 1, [], []);
	// const [data1] = await e();
	const group_id = new Array();
	data.forEach((v) => {
		group_id.push(v.group_id);
	});

	del('allot_conditions', { productid: msg.productid, group_id: { $in: group_id } });
	del('allot_conditions_group', { productid: msg.productid, role_allot_id: { $in: arr } });
	del('pub_role_allot', { productid: msg.productid, pk_val: msg.formgroup_no });
	del('auth_formgroup', { _id: msg._id, productid: msg.productid });
	del('auth_formgroup_form', { formgroup_no: msg.formgroup_no, productid: msg.productid });
	del('auth_formgroup_code', { formgroup_no: msg.formgroup_no, productid: msg.productid });
	const ret3 = await exec();
	if (ret3.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}
}
